import 'dart:ui';

import 'package:znmm/config/app_asset.dart';
import 'package:znmm/network/api_url.dart';
import 'package:znmm/network/dio_https.dart';
// import 'package:glassesin/network/graphql_service.dart';
// import 'package:glassesin/network/notify_listener.dart';
// import 'package:graphql_flutter/graphql_flutter.dart';
import '../../ProductPages/model/product_model.dart';
// import 'home_mod_data.dart';
// import 'home_query_string.dart';

class HomeMag {
  static final HomeMag _singleton = HomeMag._internal();
  factory HomeMag() {
    return _singleton;
  }

  HomeMag._internal();

  //接口1抽出来的 Swiper
  late final List<ProductModel> _swiperProducList = [];
  List<ProductModel> getSwiperProducList() => _swiperProducList;

  //接口2抽出来的 newProduct
  late final List<ProductModel> _newProducList = [];
  List<ProductModel> getNewProducList() => _newProducList;

  //接口3抽出来的 newProduct
  late final List<ProductModel> _producByCageList = [];
  List<ProductModel> getProducByGageList() => _producByCageList;

  //接口4抽出来的 postsProduct
  late final List<ProductModel> _postsProducList = [];
  List<ProductModel> getPostsProducList() => _postsProducList;

  void doSomething() {
    print("Doing something...");
  }

  //广告
  late final List<String> _bannerList = [];
  List<String> getBannerList() => _bannerList;

  void reqHomeBanner({void Function()? callback}) {
    if (_bannerList.isNotEmpty) return;
    DioHttps dioUtil = DioHttps.instance!;
    dioUtil
        .request<dynamic>(
      APIUrl.homeBanner,
      bIsShowLoading: false,
      //bIsShowResponse: true,
      method: DioMethod.get,
    )
        .then((response) {
      // 处理响应数据
      print("response:$response");
      if (response == null) {
        if (callback != null) {
          callback();
        }
        return;
      }

      _bannerList.clear();

      var dataList = response['data'] as List;
      print("dataList:${dataList.length}");

      for (int iIndex = 0; iIndex < dataList.length; iIndex++) {
        String imageStr = dataList[iIndex]["image"];
        _bannerList.add(imageStr);
      }

      if (callback != null) {
        callback();
      }
    });
  }

/*
  //------1测试接口
  void productCategGraql() {
    if (_swiperProducList.isNotEmpty) return;

    GraphQLService.performQuery(
      productCategoriesQuery,
      HttpLink(APIUrl.graphqlUrl),
      variables: productCategoriesVariables,
      //bIsShowLoading: true,
      //bShowResponse: true,
      (data) {
        if (data == null) return;
        // On success
        //print('Query successful: $data');

        var productCategories = data["productCategories"];
        if (productCategories == null) return;
        var nodesList = productCategories['nodes'] as List;

        _swiperProducList.clear();
        for (int iIndex = 0; iIndex < nodesList.length; iIndex++) {
          var jsonV = nodesList[iIndex];
          ProductModel pModel = ProductModel.fromJson(jsonV);
          if (pModel.sourceUrl.isNotEmpty && _swiperProducList.length <= 7) {
            _swiperProducList.add(pModel);
            //print("sourceUrl:${pModel.sourceUrl}");
          }
        }
        _swiperProducList.add(HomeModData.productList[2]); //追加一个测试数据
        _swiperProducList.add(HomeModData.productList[3]); //追加一个测试数据
        _swiperProducList.add(HomeModData.productList[4]); //追加一个测试数据
      },
    );
  }

  //------2测试接口
  void newProductsGraql() {
    if (_newProducList.isNotEmpty) return;

    GraphQLService.performQuery(
      newProductsQuery,
      HttpLink(APIUrl.graphqlUrl),
      //bIsShowLoading: true,
      //bShowResponse: true,
      (data) {
        if (data == null) return;
        // On success
        //print('Query successful: $data');

        var newProductsVal = data["newProducts"];
        if (newProductsVal == null) return;
        var edgesList = newProductsVal['edges'] as List;

        if (edgesList.isEmpty) {
          newProductsVal = data["featuredProducts"];
          if (newProductsVal != null) {
            edgesList = newProductsVal['edges'] as List;
          }
        }

        _newProducList.clear();
        for (int iIndex = 0; iIndex < edgesList.length; iIndex++) {
          var jsonV = edgesList[iIndex]["node"];

          ProductModel pModel = ProductModel.fromJson(jsonV);
          if (pModel.sourceUrl.isNotEmpty && _newProducList.length < 10) {
            //print("sourceUrl 2:${pModel.sourceUrl}");
            _newProducList.add(pModel);
          }
        }
        // _newProducList.add(HomeModData.productList[0]); //追加一个测试数据
        // _newProducList.add(HomeModData.productList[1]); //追加一个测试数据

        NotifyCenter().postNotification(NotifyKey.newProductKey);
      },
    );
  }

  //------3测试接口
  void getProductsByCategorySlug({String categorySlug = ""}) {
    Map<String, dynamic> productsQueryVariables = {
      'first': 10,
      'after': null,
      'orderby': null,
      'featured': true,
      'categorySlug': categorySlug,
      //'categorySlug': 'makeup-vanities',
    };

    GraphQLService.performQuery(
      productsQuery,
      HttpLink(APIUrl.graphqlUrl),
      variables: productsQueryVariables,
      //bIsShowLoading: true,
      //bShowResponse: true,
      (data) {
        if (data == null) return;
        // On success
        // print('Query successful: $data');

        var products = data["products"];
        if (products == null) return;
        var edgesList = products['edges'] as List;

        _producByCageList.clear();
        for (int iIndex = 0; iIndex < edgesList.length; iIndex++) {
          var jsonV = edgesList[iIndex]["node"];

          ProductModel pModel = ProductModel.fromJson(jsonV);
          //if (pModel.sourceUrl.isNotEmpty)
          {
            //print("sourceUrl 3:${pModel.sourceUrl}");
            _producByCageList.add(pModel);
          }
        }

        NotifyCenter().postNotification(NotifyKey.getProductByCategKey);
      },
    );
  }

  //------4测试接口
  void getPostsGraql({String categoryName = ""}) {
    Map<String, dynamic> postQueryVariables = {
      'first': 10,
      'after': null,
      'categoryName': categoryName,
    };

    GraphQLService.performQuery(
      postQuery,
      HttpLink(APIUrl.graphqlUrl),
      variables: postQueryVariables,
      //bIsShowLoading: true,
      //bShowResponse: true,
      (data) {
        if (data == null) return;
        // On success
        //print('Query successful: $data');

        var postsVal = data["posts"];
        if (postsVal == null) return;
        var nodesList = postsVal['nodes'] as List;

        _postsProducList.clear();
        for (int iIndex = 0; iIndex < nodesList.length; iIndex++) {
          var jsonV = nodesList[iIndex];

          ProductModel pModel = ProductModel.fromJson(jsonV);
          if (pModel.featuredImage.isNotEmpty) {
            //print("featuredImage 4:${pModel.featuredImage}");
            _postsProducList.add(pModel);
          }
        }

        NotifyCenter().postNotification(NotifyKey.postsProductKey);
      },
    );
  }

*/

  static List<ProductModel> productList = [
    ProductModel(
      quantity: 1,
      isFavorite: false,
      title: 'Comhar All-in-One Standing Desk Glass',
      description: "--",
      price: "469.99",
      score: 3.5,
      icon: AppAsset.chart01,
      discount: '25%',
      detail: 'Get discount for every order, only valid for today',
      imagesList: [
        AppAsset.chart01,
        AppAsset.chart02,
        AppAsset.chart03,
        AppAsset.chart04,
        AppAsset.chart05,
        AppAsset.comhar,
        AppAsset.cups,
      ],
      colors: <ProductColorModel>[
        ProductColorModel(color: const Color(0xFF616161), isSelected: true),
        ProductColorModel(color: const Color.fromARGB(255, 71, 70, 131)),
        ProductColorModel(color: const Color.fromARGB(255, 202, 86, 86)),
      ],
    ),
    ProductModel(
      isFavorite: false,
      quantity: 1,
      title: 'Ergonomic Gaming Desk with Mouse Pad',
      description: "description",
      price: "299.99",
      score: 4.5,
      icon: AppAsset.cups,
      discount: '35%',
      detail: 'Please give me a star!',
      imagesList: [
        AppAsset.desk,
        AppAsset.lamp,
        AppAsset.sofa,
        AppAsset.chart05,
        AppAsset.chart04,
      ],
      colors: <ProductColorModel>[],
    ),
    ProductModel(
      quantity: 1,
      isFavorite: false,
      title: 'Kana Pro Bamboo Standing Desk',
      description: "dummyText",
      price: "659.99",
      score: 3.0,
      icon: AppAsset.chart04,
      discount: '100%',
      detail: 'If you have any problem, contact me',
      imagesList: [
        AppAsset.chart03,
        AppAsset.chart02,
        AppAsset.chart01,
        AppAsset.sofa,
        AppAsset.lamp,
        AppAsset.desk,
      ],
      colors: <ProductColorModel>[
        ProductColorModel(color: const Color(0xFF616161), isSelected: true),
        ProductColorModel(color: const Color(0xFF212121)),
      ],
    ),
    ProductModel(
      quantity: 1,
      isFavorite: false,
      title: 'Soutien Ergonomic Office Chair',
      description: "dummyText",
      price: "349.99",
      score: 2.5,
      icon: AppAsset.desk,
      discount: '75%',
      detail: 'Wish you have a funny time',
      imagesList: [
        AppAsset.cups,
        AppAsset.comhar,
        AppAsset.chart05,
        AppAsset.chart04,
        AppAsset.chart03,
        AppAsset.chart02,
      ],
      colors: <ProductColorModel>[
        ProductColorModel(color: const Color(0xFF455a64), isSelected: true),
        ProductColorModel(color: const Color(0xFF263238)),
      ],
    ),
    ProductModel(
      quantity: 1,
      isFavorite: false,
      title: 'Theodore Standing Desk',
      description: "dummyText",
      price: "499.99",
      score: 2.8,
      icon: AppAsset.chart02,
      discount: '65%',
      detail: 'If you have any confuse, let me now',
      imagesList: [
        AppAsset.chart01,
        AppAsset.comhar,
        AppAsset.cups,
        AppAsset.desk,
        AppAsset.lamp,
      ],
      colors: <ProductColorModel>[
        ProductColorModel(color: const Color(0xFF5d4037), isSelected: true),
        ProductColorModel(color: const Color(0xFF455a64)),
      ],
    ),
  ];
}
